import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class NoticeCrawlerWithQQ {
    public static void main(String[] args) {
        startScheduledTask();
    }

    public static void startScheduledTask() {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        System.out.println("启动定时任务，每60秒检查一次公告...");
        System.out.println("开始时间: " + java.time.LocalDateTime.now());

        scheduler.scheduleAtFixedRate(() -> {
            try {
                System.out.println("\n=== 开始执行检查任务 ===");
                start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, 20, 40, TimeUnit.SECONDS);
    }


    public static void start() {
        String url = "https://www.njpta.org.cn/newsCenter/33.html";
        String targetQQ = "2096798340"; // 替换为目标QQ号

        try {
            System.out.println("开始请求URL: " + url);

            HttpResponse response = HttpRequest.get(url)
                    .timeout(30000)
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                    .execute();

            if (response.isOk()) {
                String html = response.body();
                Document doc = Jsoup.parse(html);

                // 多种选择器尝试
                List<String> selectors = List.of(
                        "ul.infos.newsCenter li",
                        ".infos.newsCenter li",
                        ".newsCenter li",
                        ".infos ul li",
                        "ul li[style*='padding: 12px 0']"
                );

                Elements noticeItems = null;
                for (String selector : selectors) {
                    noticeItems = doc.select(selector);
                    if (!noticeItems.isEmpty()) break;
                }

                if (noticeItems == null || noticeItems.isEmpty()) {
                    System.out.println("未找到公告项");
                    return;
                }

                List<String> targetNotices = new ArrayList<>();

                for (int i = 0; i < noticeItems.size(); i++) {
                    Element item = noticeItems.get(i);
                    String publishDate = "";
                    Element dateElement = item.selectFirst("div.remarkRT a");
                    if (dateElement != null) {
                        publishDate = dateElement.text().trim();
                    }

                    String title = "";
                    Element titleElement = item.selectFirst("div.infosTitle");
                    if (titleElement != null) {
                        title = titleElement.ownText().trim();
                    }

                    if ("2025-11-12".equals(publishDate)) {
                        targetNotices.add("发布日期: " + publishDate + " - 标题: " + title);
                    }
                }

                // 发送QQ通知
                if (!targetNotices.isEmpty()) {
                    System.out.println("找到 " + targetNotices.size() + " 条目标公告");

                    QQMessageSender qqSender = new QQMessageSender();
                    // 发送每条公告
                    boolean isSend = false;
                    for (String notice : targetNotices) {
                        if (notice.contains("医疗卫生机构") || notice.contains("第二人民医院")) {
                            continue;
                        }
                        qqSender.sendQQMessage(targetQQ, notice);
                        isSend = true;
                        Thread.sleep(3000); // 每条消息间隔3秒
                    }

                    if (isSend) {
                        System.out.println("=====================> 所有通知发送完成！");
                        System.exit(0);
                    } else {
                        System.out.println("不是目标消息");
                    }
                } else {
                    System.out.println("没有找到目标公告");
                }
            }
        } catch (Exception e) {
            System.out.println("程序执行错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    static class QQMessageSender {
        private Robot robot;

        public QQMessageSender() throws AWTException {
            this.robot = new Robot();
            robot.setAutoDelay(100);
        }

        public void sendQQMessage(String qqNumber, String message) {
            try {
                System.out.println("准备发送: " + message);
                System.out.println("请在3秒内切换到QQ与 " + qqNumber + " 的聊天窗口...");
                robot.delay(3000);

                // 使用剪贴板方式发送中文
                copyToClipboard(message);
                pasteFromClipboard();

                // 尝试多种发送方式
                if (!trySendMessage()) {
                    System.out.println("自动发送失败，请手动按 Alt+Enter 发送消息");
                    // 等待用户手动发送
                    robot.delay(5000);
                }

                System.out.println("消息发送流程完成");

            } catch (Exception e) {
                System.out.println("发送消息失败: " + e.getMessage());
            }
        }

        private boolean trySendMessage() {
            try {
                // 方式1: Alt+Enter（主要方式）
                System.out.println("尝试 Alt+Enter 发送...");
                sendByAltEnter();
                robot.delay(1000);

                // 方式2: Ctrl+Enter（备选）
                System.out.println("尝试 Ctrl+Enter 发送...");
                sendByCtrlEnter();
                robot.delay(1000);

                // 方式3: 直接回车（最后尝试）
                System.out.println("尝试直接回车发送...");
                sendByEnter();
                robot.delay(1000);

                return true;
            } catch (Exception e) {
                System.out.println("自动发送失败: " + e.getMessage());
                return false;
            }
        }

        private void sendByAltEnter() {
            robot.keyPress(KeyEvent.VK_ALT);
            robot.keyPress(KeyEvent.VK_ENTER);
            robot.delay(50);
            robot.keyRelease(KeyEvent.VK_ENTER);
            robot.keyRelease(KeyEvent.VK_ALT);
            robot.delay(500);
        }

        private void sendByCtrlEnter() {
            robot.keyPress(KeyEvent.VK_CONTROL);
            robot.keyPress(KeyEvent.VK_ENTER);
            robot.delay(50);
            robot.keyRelease(KeyEvent.VK_ENTER);
            robot.keyRelease(KeyEvent.VK_CONTROL);
            robot.delay(500);
        }

        private void sendByEnter() {
            robot.keyPress(KeyEvent.VK_ENTER);
            robot.delay(50);
            robot.keyRelease(KeyEvent.VK_ENTER);
            robot.delay(500);
        }

        private void copyToClipboard(String text) {
            try {
                StringSelection stringSelection = new StringSelection(text);
                Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
                clipboard.setContents(stringSelection, null);
                robot.delay(300);
            } catch (Exception e) {
                System.out.println("复制到剪贴板失败: " + e.getMessage());
            }
        }

        private void pasteFromClipboard() {
            try {
                robot.keyPress(KeyEvent.VK_CONTROL);
                robot.keyPress(KeyEvent.VK_V);
                robot.delay(100);
                robot.keyRelease(KeyEvent.VK_V);
                robot.keyRelease(KeyEvent.VK_CONTROL);
                robot.delay(300);
            } catch (Exception e) {
                System.out.println("粘贴失败: " + e.getMessage());
            }
        }
    }
}